﻿using SlimDX;
using SlimDX.Direct3D9;
using System.Drawing;
using System.Runtime.InteropServices;

namespace SlimDXSample
{
    static class VertexHelper
    {
        [StructLayout(LayoutKind.Sequential)]
        public struct PositionColored
        {
            public static readonly VertexFormat FVF = VertexFormat.Position | VertexFormat.Diffuse;
            public static readonly int Stride = Vector3.SizeInBytes + sizeof(int);

            public Vector3 Position;
            public int Color;

            public PositionColored(Vector3 pos, int col)
            {
                Position = pos;
                Color = col;
            }
        }


        // Returns a colored quad as a vertex element array

        public static VertexHelper.PositionColored[] BillBoardColored()
        {
            return BillBoardColored(1.0f);
        }

        public static VertexHelper.PositionColored[] BillBoardColored(float size)
        {
            PositionColored[] b = new PositionColored[4];

            b[0].Position.X = -size;
            b[0].Position.Y = size;
            b[1].Position.X = size;
            b[1].Position.Y = size;
            b[2].Position.X = size;
            b[2].Position.Y = -size;
            b[3].Position.X = -size;
            b[3].Position.Y = -size;
            b[0].Position.Z = b[1].Position.Z = b[2].Position.Z = b[3].Position.Z = 0.0f;
            b[0].Color = b[1].Color = b[2].Color = b[3].Color = Color.Black.ToArgb();

            return b;
        }


        // Returns a colored quad as a vertex buffer

        public static VertexBuffer BillBoardColoredVB(Device device)
        {
            return BillBoardColoredVB(device, 1.0f);
        }

        public static VertexBuffer BillBoardColoredVB(Device device, float size)
        {
            VertexBuffer vb = new VertexBuffer(device, 4 * PositionColored.Stride, Usage.None,
                PositionColored.FVF, Pool.SystemMemory);
            DataStream ds = vb.Lock(0, 4 * PositionColored.Stride, LockFlags.None);
            VertexHelper.PositionColored[] vertexArray =
                VertexHelper.BillBoardColored(size);
            ds.WriteRange(vertexArray);

            return vb;
        }


        // Render primitives

        public static void DrawColored(VertexBuffer buffer)
        {
            buffer.Device.SetStreamSource(0, buffer, 0, PositionColored.Stride);
            buffer.Device.VertexFormat = PositionColored.FVF;
            buffer.Device.DrawPrimitives(PrimitiveType.TriangleFan, 0, 2);
        }
    }
}
